﻿using Microsoft.AspNetCore.Http;
using TianShu.Domain;
using TianShu.SqlSugarCore.SqlSugarFactory;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Text;
using TianShu.Domain.Services;
using TianShu.Users;
using TianShu.Uow;
using TianShu.SqlSugarCore.SqlSugarFactory.uow;
using TianShu.Domain.Entities;
using TianShu.Threading;

namespace TianShu.SqlSugarCore.Services
{
    public abstract class DalService : DomainService, IDalService, IUnitOfWorkEnabled
    {
        
        public ISqlSugarClient Db { get => AsyncHelper.RunSync<ISqlSugarClient>(() => LazyServiceProvider.LazyGetRequiredService<IUowSqlSugarFactory>().GetClient()); }
        protected ICurrentUser CurrentUser => LazyServiceProvider.LazyGetRequiredService<ICurrentUser>();

        protected IUnitOfWorkManager UnitOfWorkManager => LazyServiceProvider.LazyGetRequiredService<IUnitOfWorkManager>();
        protected IUnitOfWork CurrentUnitOfWork => UnitOfWorkManager?.Current;

        protected ISugarQueryable<TEntity> GetAll<TEntity>()
        {
            var dataFilterStr = typeof(TEntity).GetDataFilter(CurrentTenant);
            return Db.Queryable<TEntity>().Where(dataFilterStr);
        }
        /// <summary>
        /// 合并group by 之后的字段值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string GroupConcat<T>(T str)
        {
            throw new NotSupportedException("Can only be used in expressions");
        }
        

        public DalService()
        {
        }
    }

    public abstract class DalService<TEntity> : DalService where TEntity : class, IEntity, new()
    {
        public ISimpleClient<TEntity> DbSet { get => new SimpleClient<TEntity>(Db); }

        public DalService()
        {

        }
    }

}
